package com.zbkj.service.service.monitor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.monitor.ZfbMonitorEquipment;
import com.zbkj.common.model.monitor.ZfbMonitorOrder;
import com.zbkj.common.model.monitor.ZfbMonitorTrafficSetMeal;
import com.zbkj.common.monitorchannel.vo.MonitorChannelEquipmentStatusVo;
import com.zbkj.common.monitorchannel.vo.MonitorSetOpenFlagVo;
import com.zbkj.common.monitorchannel.vo.ThirdMonitorResultVo;
import com.zbkj.common.response.monitor.ZfbEquipmentOrderResponse;
import com.zbkj.service.dao.monitor.ZfbMonitorEquipmentMapper;
import com.zbkj.service.dao.monitor.ZfbMonitorOrderMapper;
import com.zbkj.service.dao.monitor.ZfbMonitorTrafficSetMealMapper;
import com.zbkj.service.service.MerchantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @ClassName: ZfbMonitorOpenCloseServiceImpl
 * @Description: TODO
 * @Author: fanbing
 * @Date: 2024/12/7 18:54
 * @Version: V1.0
 **/
@Service
@Slf4j
public class ZfbMonitorOpenCloseServiceImpl implements IZfbMonitorOpenCloseService {

    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ZfbMonitorOrderMapper zfbMonitorOrderMapper;
    @Autowired
    private ZfbMonitorTrafficSetMealMapper zfbMonitorTrafficSetMealMapper;

    @Autowired
    private IZfbMonitorEquipmentService zfbMonitorEquipmentService;


    @Autowired
    private ZfbMonitorEquipmentMapper zfbMonitorEquipmentMapper;


    @Override
    public boolean checkOpenOrClose(String license, Integer merchantId) {
        try {

            Merchant merchant = merchantService.getById(merchantId);
            if (ObjectUtil.isNull(merchant)) {
                log.info("商户不存在merchantId==={}", merchantId);
                return Boolean.FALSE;
            }
            MonitorChannelEquipmentStatusVo equipmentStatus = zfbMonitorEquipmentService.getEquipmentStatus(license);
            if (ObjectUtil.isNull(equipmentStatus)) {
                log.info("#checkOpenOrClose#设备不存在license={}", license);
                return Boolean.FALSE;
            }
            String did = equipmentStatus.getDid();

            // 监控类型 1=免费  2=付费
            Integer monitorType = merchant.getMonitorType();
            // 免费时长 1=免费一个月 2=免费一个季度 3=免费一年 4=免费两年  5=免费三年
            Integer freeMonitorTime = merchant.getFreeMonitorTime();

            String monitorStartTime = merchant.getMonitorStartTime();
            boolean isFree = checkIsFree(freeMonitorTime, monitorStartTime);


            MonitorSetOpenFlagVo openFlagVo = new MonitorSetOpenFlagVo();
            openFlagVo.setLicense(license);
            // 设备开关状态, 0.关闭; 1.打开;
            openFlagVo.setStatus("1");
            openFlagVo.setDid(did);
            log.info("#checkOpenOrClose#设备是否开启关闭={};freeMonitorTime={};monitorStartTime={},merchantId={};license={}", isFree, freeMonitorTime, monitorStartTime, merchantId, license);
            if (isFree) {
                zfbMonitorEquipmentService.wakeUpEquipment(license);
                Thread.sleep(1000 * 60 * 2);
                JSONObject jsonObject = zfbMonitorEquipmentService.v3SetOpenFlag(openFlagVo, 0);
                log.info("#checkOpenOrClose#setOpenFlag开启免费开启 resultVo==={};;openFlagVo==={};merchantId={}", JSON.toJSONString(jsonObject), JSON.toJSONString(openFlagVo), merchantId);
                return Boolean.TRUE;
            }

            ZfbMonitorOrder zfbMonitorOrder = zfbMonitorOrderMapper.selectOne(new LambdaQueryWrapper<ZfbMonitorOrder>()
                    .eq(ZfbMonitorOrder::getOrderStatus, 1)
                    .eq(ZfbMonitorOrder::getMerchantId, merchantId)
                    .orderByDesc(ZfbMonitorOrder::getId).last("limit 1"));

            if (ObjectUtil.isNotNull(zfbMonitorOrder)) {
                ZfbMonitorTrafficSetMeal monitorTrafficSetMeal = zfbMonitorTrafficSetMealMapper.selectById(zfbMonitorOrder.getProductId());

                if (ObjectUtil.isNotNull(monitorTrafficSetMeal)) {
                    ZfbEquipmentOrderResponse zfbEquipmentOrderResponse = new ZfbEquipmentOrderResponse();
                    zfbEquipmentOrderResponse.setOrderNo(zfbMonitorOrder.getOrderNo());
                    zfbEquipmentOrderResponse.setProductName(monitorTrafficSetMeal.getName());
                    zfbEquipmentOrderResponse.setProductType(monitorTrafficSetMeal.getType());
                    zfbEquipmentOrderResponse.setCreateTime(zfbMonitorOrder.getCreateTime());
                    zfbMonitorEquipmentService.wakeUpEquipment(license);
                    Thread.sleep(1000 * 60 * 2);
                    JSONObject jsonObject = zfbMonitorEquipmentService.v3SetOpenFlag(openFlagVo, 0);
                    log.info("#checkOpenOrClose#setOpenFlag开启下单开启 resultVo==={};;openFlagVo==={};merchantId={}", JSON.toJSONString(jsonObject), JSON.toJSONString(openFlagVo), merchantId);
                    return Boolean.TRUE;
                }
            }

            // 设备开关状态, 0.关闭; 1.打开;
            openFlagVo.setStatus("0");
            zfbMonitorEquipmentService.wakeUpEquipment(license);
            Thread.sleep(1000 * 60 * 2);
            JSONObject jsonObject = zfbMonitorEquipmentService.v3SetOpenFlag(openFlagVo, 0);
            log.info("#checkOpenOrClose#关闭setOpenFlag resultVo==={};;openFlagVo==={};merchantId={}", JSON.toJSONString(jsonObject), JSON.toJSONString(openFlagVo), merchantId);
            return Boolean.FALSE;
        } catch (Exception e) {
            log.info("#checkOpenOrClose#异常license={},merchantId={}; e={}", license, merchantId, e);
            log.error("#checkOpenOrClose#异常 e={}", e);
        }
        return Boolean.FALSE;
    }

    private boolean checkIsFree(Integer freeMonitorTime, String monitorStartTimeStr) {
        // 解析时间字符串到 LocalDateTime
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime monitorStartTime = LocalDateTime.parse(monitorStartTimeStr, formatter);

        if (ObjectUtil.isNull(freeMonitorTime) || ObjectUtil.isNull(monitorStartTime)) {
            return Boolean.FALSE;
        }
        if (freeMonitorTime == 1) {
            LocalDateTime localDateTime = monitorStartTime.plusDays(30);
            return localDateTime.isAfter(LocalDateTime.now());
        }
        if (freeMonitorTime == 2) {
            LocalDateTime localDateTime = monitorStartTime.plusDays(90);
            return localDateTime.isAfter(LocalDateTime.now());
        }
        if (freeMonitorTime == 3) {
            LocalDateTime localDateTime = monitorStartTime.plusYears(1);
            return localDateTime.isAfter(LocalDateTime.now());
        }
        if (freeMonitorTime == 4) {
            LocalDateTime localDateTime = monitorStartTime.plusYears(2);
            return localDateTime.isAfter(LocalDateTime.now());
        }
        if (freeMonitorTime == 5) {
            LocalDateTime localDateTime = monitorStartTime.plusYears(5);
            return localDateTime.isAfter(LocalDateTime.now());
        }
        return Boolean.FALSE;
    }

    @Override
    public void openAll(Integer merchantId) {
        List<ZfbMonitorEquipment> zfbMonitorEquipments = zfbMonitorEquipmentMapper.selectList(new LambdaQueryWrapper<ZfbMonitorEquipment>().eq(ZfbMonitorEquipment::getMerchantId, merchantId));

        for (ZfbMonitorEquipment equipment : zfbMonitorEquipments) {
            MonitorSetOpenFlagVo openFlagVo = new MonitorSetOpenFlagVo();
            openFlagVo.setLicense(equipment.getLicense());
            // 设备开关状态, 0.关闭; 1.打开;
            openFlagVo.setStatus("1");
            ThirdMonitorResultVo thirdMonitorResultVo = zfbMonitorEquipmentService.setOpenFlag(openFlagVo);
            log.info("#checkOpenOrClose#openAll resultVo==={};;openFlagVo==={}", JSON.toJSONString(thirdMonitorResultVo), JSON.toJSONString(openFlagVo));
            return;
        }


    }
}
